import React, { useEffect, useRef, useState } from 'react';
import { message } from 'antd';
import classNames from 'classnames';
import styles from './index.less';
import { InnerUpload } from '@/pages/pc/components/Upload';
import { uid } from '@/utils';
import { allGet } from '@/services/pc';

const getAliyunAuth = async (data = {} as any) => {
  const response = await allGet({
    params: {
      mod: 'video',
      do: 'aliyun',
      version: 'pc1.0',
      action: 'CreateUploadVideo',
      CateId: '1000422147',
      ...data,
    },
  });
  return response?.data || {};
};

const refreshAliyunAuth = async (data = {}) => {
  const response = await allGet({
    params: { mod: 'video', do: 'aliyun', version: 'pc1.0', action: 'RefreshUploadVideo', ...data },
  });
  return response?.data || {};
};

const ProcessBarUpload = ({
  className = '',
  style = {},
  size = 50000,
  value = [] as any,
  payload = {},
  aliyunAuthPayload = {},
  action,
  name = 'file',
  videoUploadto = 'AliyunVideo',
  tips = '点击上传',
  onBeforeUpload = async (file, preFile) => true,
  prefix = <i />,
  successText = '',
  onChange = (value) => null,
  replaceOnMax1 = true,
  controlled = false,
  onSuccess = (filelist, file) => true as any,
  onRemove = () => true,
}) => {
  const [fileList, setFlieList] = useState<any[]>(value);
  // const fileListCount = useRef(0);
  const init = async () => {};
  const UploadRef = useRef<any>();

  useEffect(() => {
    init();
  }, []);
  useEffect(() => {
    if (controlled) {
      setFlieList(value);
    }
  }, [value]);

  const beforeUpload = async (file) => {
    const preFile = fileList[0];
    if ((await onBeforeUpload?.(file, preFile)) === false) return false;

    // 尺寸不符合
    const isSizeOK = file.size <= 1024 * 1024 * size;
    if (!isSizeOK) {
      message.error(`文件大小不能超过 ${size} Mb`);
      return false;
    }

    file.key = file?.uid || uid();

    return file;
  };
  const handleUploadChange = async (fileList, file) => {
    const newFileList = [fileList[fileList.length - 1]];
    setFlieList(newFileList);
    onChange?.(newFileList, file);
  };
  const handleSuccess = async (fileList, file) => {
    console.log(fileList, file);
    onSuccess?.(fileList, file);
  };

  const upLoadProps = {
    fileList,
    onChange: handleUploadChange,
    name,
    action,
    multiple: false,
    data: () => payload,
    beforeUpload: beforeUpload,
    onSuccess: handleSuccess,
    videoUploadto,
    getAliyunAuth: (data) => {
      return getAliyunAuth({ ...data, ...aliyunAuthPayload });
    },
    refreshAliyunAuth: (data) => {
      return refreshAliyunAuth({ ...data, ...aliyunAuthPayload });
    },
  };

  const statusInfo = () => {
    const file = fileList[fileList.length - 1];
    if (file?.status === 'done') {
      return { text: successText || `已上传成功，点击可重新上传 （${file.name}）`, ...file };
    }
    if (file?.status === 'uploading') {
      return { text: `${file.name} 上传中...`, ...file };
    }
    if (file?.status === 'error') {
      return { text: '上传失败，请重新上传', ...file };
    }
    return { text: tips, status: 'none' };
  };
  const handleRemoveFile = () => {
    const file = fileList[fileList.length - 1];
    onRemove?.();
    UploadRef.current?.removeFile?.(file);
  };
  const info = statusInfo();
  return (
    <div
      className={classNames(
        styles.uploadprocess,
        className,
        `uploadprocess-process-${info.status}`,
      )}
      style={style}
    >
      <InnerUpload ref={UploadRef} {...(upLoadProps as any)} className={styles.upload}>
        <div className={classNames(styles.process, 'uploadprocess-process', styles[info.status])}>
          <i
            className={classNames(styles.processInner, 'uploadprocess-process-inner')}
            style={{ width: info.status === 'done' ? '100%' : `${info.percent || 0}%` }}
          />
          <div className={classNames(styles.textWrapper, 'uploadprocess-process-text')}>
            {prefix}
            <span className={styles.text}>{info.text}</span>
          </div>

          <div className={classNames(styles.percent, 'uploadprocess-process-percent')}>
            <i className={classNames(styles['icon-success'], 'uploadprocess-process-icon')} />
            <i className={styles['icon-delete']} onClick={handleRemoveFile} />
            {info.status === 'uploading' && `${info.percent || 0}%`}
          </div>
        </div>
      </InnerUpload>
    </div>
  );
};

export default ProcessBarUpload;
